package com.example.text4;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private TextView tv_artist, tv_title;
    ImageView iv_previous, iv_next, iv_pause, iv_music;

    List<Data> list = new ArrayList<>();
    ListView listView;
    private Intent intent;

    private MusicReciver reciver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        listView = findViewById(R.id.lv);
        intent = new Intent(this, PlayService.class);
        startService(intent);
        reciver = new MusicReciver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("musicchange");
        filter.addAction("playpause");
        registerReceiver(reciver,filter);

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if(item.getItemId()==R.id.menu_refresh){
                    refreshMusic();
                }
                return true;
            }
        });
        String read = Manifest.permission.READ_MEDIA_AUDIO;
        if (ActivityCompat.checkSelfPermission(this, read)== PackageManager.PERMISSION_GRANTED){
            list = getMusic(this);
        }else {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{read},100);
        }
        listView.setAdapter(new Myadapter(list));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                intent.putExtra("action", "play");
                intent.putExtra("pos", position);
                startService(intent);
                refresh(position);
            }
        });
        tv_title=findViewById(R.id.singb);
        tv_artist=findViewById(R.id.playerb);
        iv_music=findViewById(R.id.imageb);
        iv_previous=findViewById(R.id.pre);
        iv_next=findViewById(R.id.next);
        iv_pause=findViewById(R.id.pus);
        iv_previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent.putExtra("action", "pervious");
                startService(intent);
            }
        });
        iv_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent.putExtra("action", "next");
                startService(intent);

            }
        });
        iv_pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent.putExtra("action", "pause");
                startService(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(reciver);
        super.onDestroy();
    }

    public static List<Data> getMusic(Context context){
        List<Data> list = new ArrayList<>();
        ContentResolver contentResolver = context.getContentResolver();
        Cursor query = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{
                MediaStore.Audio.AudioColumns._ID,
                MediaStore.Audio.AudioColumns.ARTIST,
                MediaStore.Audio.AudioColumns.TITLE,
                MediaStore.Audio.AudioColumns.DURATION,
                MediaStore.Audio.Media.DATA
        }, null, null, null);
        System.out.println("--------------------------------------");
        while (query.moveToNext()){
            int id = query.getInt(0);
            String title = query.getString(1);
            String player = query.getString(2);
            long time = query.getLong(3);
            String url = query.getString(4);
            list.add(new Data(id, title, player, url, time));
            System.out.println(title+"-----"+player + "--------" + time);
        }
        System.out.println("--------------------------------------");
        query.close();
        return list;
    }
    public void refreshMusic(){
        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        String path = file.getAbsolutePath();
        MediaScannerConnection.scanFile(this, new String[]{path}, null, new MediaScannerConnection.OnScanCompletedListener() {
            @Override
            public void onScanCompleted(String path, Uri uri) {
                System.out.println("============"+ path);
            }
        });
    }
    public void refresh(int postion){
        Data music = list.get(postion);
        tv_artist.setText(music.getPlayer());
        tv_title.setText(music.getSing());
        iv_pause.setImageResource(R.drawable.pause);
        Bitmap bitmap = null;
        bitmap = Myadapter.getArtworkFromFile(MainActivity.this, music.getId());
        if (bitmap!=null){
            iv_music.setImageBitmap(bitmap);
        }
    }
    class MusicReciver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("musicchange".equals(action)){
                int pos = intent.getIntExtra("pos", 0);
                refresh(pos);
            }else if ("playpause".equals(action)){
                boolean playing = intent.getBooleanExtra("playing", false);
                if (playing){
                    iv_pause.setImageResource(R.drawable.arrow);
                }else {
                    iv_pause.setImageResource(R.drawable.pause);
                }
            }

        }
    }
}